import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author: knowno
 * @create: 2024-09-20 09:04
 * @Version 1.0
 **/
public class TestTransaction {
    public static void main(String[] args) throws SQLException {

        //原始事务处理代码

        // 前提，先拿到一个链接对象
        Connection conn = DBUtil2.getConn();
        //1 .开启事务，设置自动提交为false
        conn.setAutoCommit(false);

        //2 设置sql，执行语句
        //账号1的用户执行扣款
        String sql1 = "update t_account set balance=balance-100 where id=1";
        PreparedStatement preparedStatement = conn.prepareStatement(sql1);

        System.out.println(preparedStatement);
        //这里i就是我们后面是提交还是回滚的条件
        int i = preparedStatement.executeUpdate();

        //手动引发异常
        System.out.println(1 / 0);

        //账号2的用户执行增加余额操作
        String sql2 = "update t_account set balance=balance+100 where id=2";
        preparedStatement = conn.prepareStatement(sql2);

        System.out.println(preparedStatement);
        //这里i就是我们后面是提交还是回滚的条件
        int j = preparedStatement.executeUpdate();

        if (i == 1 && j == 1) {
            //3 手动提交
            conn.commit();
            System.out.println("转账成功");
        } else {
            //3 失败的,回滚
            conn.rollback();
            System.out.println("转账失败");
        }

        //释放资源
        preparedStatement.close();
        conn.close();


    }
}
